package com.rightsidetech.http.controller.agentApp.stork;

import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.base.TimeQueryRequest;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.mall.dto.response.CommodityInfoResp;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.system.dtos.request.AgentAppStoreStorkReq;
import com.rightsidetech.system.dtos.request.AgentAppStorkListReq;
import com.rightsidetech.system.dtos.response.*;
import com.rightsidetech.system.dtos.request.store.StoreStockReq;
import com.rightsidetech.system.dtos.response.store.StoreStorkExceedResp;
import com.rightsidetech.system.dtos.response.store.StoreStorkResp;
import com.rightsidetech.system.dtos.response.store.StoreStorkSearchReq;
import com.rightsidetech.system.entity.SysStoreReplenishDetails;
import com.rightsidetech.system.entity.SysStoreStock;
import com.rightsidetech.system.service.SysAgentInfoService;
import com.rightsidetech.system.service.SysStoreInfoService;
import com.rightsidetech.system.service.SysStoreStorkService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2022-01-12 14:20
 */
@Slf4j
@RestController
@RequestMapping("/agentApp/stork")
@ShenyuSpringMvcClient(path = "/agentApp/stork/**")
@Api(tags = "代理商app库存相关")
public class AgentAppStockController extends BaseController {
    @Resource
    private SysStoreStorkService sysStoreStorkService;
    @Resource
    private MallCommodityService mallCommodityService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;

    @Log
    @Token
    @ApiOperation("门店库存")
    @GetMapping("/listStoreAll")
    public ResponseData<PageInfo<SysStoreStorkAppResp>> listStoreAll(StoreStockReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long agentLoginId = Long.parseLong(getAttribute());
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (ObjectUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.NOAGENT);
        }
        ResponseData<PageInfo<SysStoreStorkAppResp>> listResponseData = sysStoreStorkService.listAgentAll(req, agentInfoId);
        if (listResponseData.getCodeId() == 1) {
            List<SysStoreStorkAppResp> resData = listResponseData.getResData().getList();
            if (!CollectionUtils.isEmpty(resData)){
                for (SysStoreStorkAppResp resp : resData) {
                    resp.setImg(mallCommodityService.selectImg(resp.getCommodityId()));
                }
            }
        }
        return listResponseData;
    }

    @Log
    @Token
    @GetMapping("/storeList")
    @ApiOperation("门店列表")
    public ResponseData<List<StoreStorkResp>> page(StoreStorkSearchReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long agentLoginId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (StringUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreStorkService.storeStorkPage(req, agentInfoId);

    }

    @Log
    @Token
    @GetMapping("/timeOutStock")
    @ApiOperation("过期提醒库存")
    public ResponseData<List<StoreStorkExceedResp>> timeOutStock() {
        Long agentLoginId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (StringUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreStorkService.storeStorkExceed(agentInfoId);

    }

    @Log
    @Token
    @GetMapping("/timeOutStockInfo")
    @ApiOperation("过期提醒库存详情")
    public ResponseData<List<SysStoreStorkDetailsAppResp>> timeOutStockInfo(Long storeId) {
        ResponseData<List<SysStoreStorkDetailsAppResp>> listResponseData = sysStoreStorkService.timeOutDetails(storeId);
        for (SysStoreStorkDetailsAppResp resp : listResponseData.getResData()) {
            resp.setImg(mallCommodityService.selectImg(resp.getCommodityId()));
        }
        return listResponseData;

    }

    @Log
    @Token
    @ApiOperation("过期换货")
    @PostMapping("/afterCommodity")
    public ResponseData afterCommodity(@RequestBody AgentAppStoreStorkReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long num = 0L;
        Long agentLoginId = Long.parseLong(getAttribute());
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        List<AgentAppStorkListReq> commodityList = req.getStoreList();
        if (StringUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        for (AgentAppStorkListReq listReq : commodityList) {
            num = listReq.getNum() + num;
        }
        // 向补货记录表中添加数据
        ResponseData responseData = sysStoreStorkService.saveAfterStork(req,agentLoginId,num);
        if (responseData.getCodeId() != 1) {
            return responseData;
        }
        List<SysStoreReplenishDetails> addDetails = new ArrayList();
        for (AgentAppStorkListReq list:commodityList){
            SysStoreStock stock = sysStoreStorkService.selectByPrimaryKey(list.getStockId());
            if (ObjectUtils.isEmpty(stock)) {
                return ResponseData.fail("未在库存中找到已存在的商品");
            }
            // ...
            if(list.getNum()>sysStoreStorkService.findExpiredNum(list.getStockId())){
                return ResponseData.fail("输入的过期商品数量大于过期数量");
            }
            SysStoreReplenishDetails details = new SysStoreReplenishDetails();
            details.setReplenishId((Long) responseData.getResData());
            details.setCommodityId(stock.getCommodityId());
            details.setCommoditySpecsId(stock.getCommoditySpecsId());
            details.setCommoditySpecs(stock.getCommoditySpecs());
            details.setBrandName(stock.getBrandName());
            details.setCommodityName(stock.getCommodityName());
            details.setTypeName(stock.getTypeName());
            details.setNum(list.getNum());
            details.setHaveStock(list.getNum());
            details.setCreatedAt(new Date());
            addDetails.add(details);
        }
        for (SysStoreReplenishDetails list:addDetails){
           if(!StringUtils.isEmpty(list)) {
               sysStoreStorkService.insertSelective(list);
           }
        }
        return ResponseData.success();
    }

    @Log
    @Token
    @ApiOperation("门店补货")
    @PostMapping("/saveStork")
    public ResponseData saveStork(@RequestBody AgentAppStoreStorkReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<AgentAppStorkListReq> storeList = req.getStoreList();
        Long num = 0L;
        Long agentLoginId = Long.parseLong(getAttribute());

        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);

        if (StringUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        for (AgentAppStorkListReq listReq : storeList) {
            num = listReq.getNum() + num;
        }
        // 更新补货记录表 返回补货记录id
        ResponseData responseData = sysStoreStorkService.saveStork(req, agentLoginId, num);
        if (responseData.getCodeId() != 1) {
            return responseData;
        }

        SysStoreReplenishDetails details = new SysStoreReplenishDetails();
        for (AgentAppStorkListReq listReq : storeList) {
            if (!StringUtils.isEmpty(listReq.getId())) {
                ResponseData<List<CommodityInfoResp>> listResponseData = mallCommodityService.selectMallInfo(listReq.getId(), agentInfoId);
                CommodityInfoResp resp = listResponseData.getResData().get(0);

                //库存增加
                SysStoreStock sysStoreStock = sysStoreStorkService.selectCountStock(req.getStoreId(), listReq.getId());
                if (ObjectUtils.isEmpty(sysStoreStock)) {
//                    Long sum = sysStoreStock.getNum() + listReq.getNum();
//                    sysStoreStorkService.updateStorkNum(req.getStoreId(), listReq.getId(), sum);
//                } else {
                    //库存新增
                    SysStoreStock stock = new SysStoreStock();
                    stock.setStoreId(req.getStoreId());
                    stock.setCommodityId(resp.getCommodityId());
                    stock.setCommoditySpecsId(resp.getId());
                    stock.setCommodityName(resp.getCommodityName());
                    stock.setTypeName(resp.getTypeName());
                    stock.setBrandName(resp.getBrandName());
                    stock.setCommoditySpecs(StringUtils.isEmpty(resp.getCommoditySpecs()) ? null : resp.getCommoditySpecs() );
                    stock.setNum(0L);
                    stock.setCreatedAt(new Date());
                    sysStoreStorkService.insertStockSelective(stock);
                }
                //库存记录增加
//                if (!StringUtils.isEmpty(responseData.getResData())) {
//                    details.setReplenishId((Long) responseData.getResData());
//                    details.setCommodityId(resp.getCommodityId());
//                    details.setCommoditySpecsId(resp.getId());
//                    details.setCommoditySpecs(resp.getCommoditySpecs());
//                    details.setBrandName(resp.getBrandName());
//                    details.setCommodityName(resp.getCommodityName());
//                    details.setTypeName(resp.getTypeName());
//                    details.setNum(listReq.getNum());
//                    details.setHaveStock(listReq.getNum());
//                    details.setCreatedAt(new Date());
//                    num = listReq.getNum() + num;
//                    // 更新了补货详情表
//                    sysStoreStorkService.insertSelective(details);
//                }
            } else {
                SysStoreStock stock = sysStoreStorkService.selectByPrimaryKey(listReq.getStockId());
                if (ObjectUtils.isEmpty(stock)) {
                    return ResponseData.fail("未在库存中找到已存在的商品");
                }
                Long countNum = listReq.getNum() + stock.getNum();
//                sysStoreStorkService.updateStockNum(listReq.getStockId(), countNum);

                details.setReplenishId((Long) responseData.getResData());
                details.setCommodityId(stock.getCommodityId());
                details.setCommoditySpecsId(stock.getCommoditySpecsId());
                details.setCommoditySpecs(stock.getCommoditySpecs());
                details.setBrandName(stock.getBrandName());
                details.setCommodityName(stock.getCommodityName());
                details.setTypeName(stock.getTypeName());
                details.setNum(listReq.getNum());
                details.setHaveStock(listReq.getNum());
                details.setCreatedAt(new Date());
                num = listReq.getNum() + num;
                sysStoreStorkService.insertSelective(details);
            }

        }
        return ResponseData.success();
    }

    @Log
    @Token
    @ApiOperation("补货选择")
    @GetMapping("/mallStork")
    public ResponseData<List<CommodityInfoResp>> mallStork(Long storeId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long agentLoginId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (StringUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        List <CommodityInfoResp> commodityInfoResps = mallCommodityService.selectMallInfo(null, agentInfoId).getResData();
        List<Long> commoditySpecsIds = sysStoreStorkService.selectCommoditySpecsIdByStoreId(storeId);
        for (CommodityInfoResp commodityInfoResp:commodityInfoResps){
            for (Long commodityResps:commoditySpecsIds){
                if(commodityInfoResp.getId().equals(commodityResps)){
                    commodityInfoResp.setHaveCommodity((byte)0);
                }
            }
        }
        return ResponseData.success(commodityInfoResps);
    }

    @Log
    @Token
    @PostMapping("/del")
    @ApiOperation("删除库存")
    public ResponseData del(@RequestBody DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        return sysStoreStorkService.delStock(req.getId());

    }

    @Log
    @Token
    @GetMapping("/replenish")
    @ApiOperation("补货记录")
    public ResponseData<PageInfo<SysAgentStorkReplenishListResp>> replenish(TimeQueryRequest timeQueryRequest) {
        Long agentLoginId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (StringUtils.isEmpty(agentInfoId)) {
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreStorkService.listReplenishAgent(agentInfoId,timeQueryRequest);
    }

    @Log
    @Token
    @GetMapping("/replenishInfo")
    @ApiOperation("补货详情")
    public ResponseData<List<SysStoreStorkDetailsAppResp>> replenishInfo(Long id) {
        if (StringUtils.isEmpty(id)) {
            return ResponseData.fail("记录id不能为空");
        }
        ResponseData<List<SysStoreStorkDetailsAppResp>> listResponseData = sysStoreStorkService.listReplenishInfo(id);
        for (SysStoreStorkDetailsAppResp resp : listResponseData.getResData()) {
            resp.setImg(mallCommodityService.selectImg(resp.getCommodityId()));
        }
        return listResponseData;
    }


}
